﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace ra2Launcher
{
    public class Config
    {
        public List<string> Executables = new List<string>();
        private string CurrentProcessName = "";//用于向外传递异常
        public Config(string cfgFPath) 
        {
            if (File.Exists(cfgFPath))
            {

                FileStream cfgFstream = new FileStream(cfgFPath, FileMode.OpenOrCreate);
                StreamReader cfgFReader = new StreamReader(cfgFstream);
                string lines;
                while((lines = cfgFReader.ReadLine()) != null)
                {
                    if (lines.Contains("\\"))//如果是绝对路径，直接加入表；
                    {
                        this.Executables.Add(lines);
                    }
                    else//如果路径缺省
                    {
                        if(lines.Contains("$"))
                        {
                            this.Executables.Add(lines.Replace("$", "$" + AppDomain.CurrentDomain.BaseDirectory));
                        }
                        else
                        {
                            this.Executables.Add(AppDomain.CurrentDomain.BaseDirectory + lines);
                        }
                    }
                }
                cfgFReader.Close();
                cfgFstream.Close();
            }
            else
            {
                File.Create(cfgFPath).Close();
            }
        }
        
        public void RunExecutables()
        {
            ProcessStartInfo psInfo;
            List<Process> ps = new List<Process>(Process.GetProcesses());
            try
            {
                Executables.ForEach(exeName =>
                {
                    if (exeName.StartsWith("$"))//$开头的以管理员身份启动
                    {
                        string realExeName = exeName.Remove(0, 1);//去掉开头的$
                        this.CurrentProcessName = realExeName;
                        psInfo = new ProcessStartInfo(realExeName);
                        psInfo.Verb = "runas";
                        Process.Start(psInfo);

                    }
                    else//否则以普通用户权限启动
                    {
                        this.CurrentProcessName = exeName;
                        psInfo = new ProcessStartInfo(exeName);
                        Process.Start(psInfo);
                    }
                });
            }catch(Exception)
            {
                throw new Exception("进程"+this.CurrentProcessName+"无法启动");
            }
        }
    }
}
